package StudyCode.summary.myfile;

import java.nio.file.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class WatchAImageFolder {
	public static void main(String[] args) throws Exception {
		final Path path = Paths.get("E:/Copy");
		WatchService watchService = FileSystems.getDefault().newWatchService();
		path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
		OUTERMOST:
		while (true) {
			WatchKey key = watchService.poll(11, TimeUnit.SECONDS);
			if (key == null) {
				System.out.println("被取消!");
				break;
			} else {
				for (WatchEvent<?> watchEvent : key.pollEvents()) {
					WatchEvent.Kind<?> kind = watchEvent.kind();
					if (kind == StandardWatchEventKinds.OVERFLOW) {
						continue;
					}
					if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
						WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
						Path filename = watchEventPath.context();
						Path child = path.resolve(filename);
						if (Files.probeContentType(child).equals("image/jpeg")) {
							SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
							System.out.println("事件对象: " + dateFormat.format(new Date()));
						} else {
							System.out.println("不是图片");
							break OUTERMOST;
						}
					}
				}
				boolean valid = key.reset();
				if (!valid) {
					break;
				}
			}
		}
		watchService.close();
	}
}
